
namespace('videomaton');

videomaton.Counter = Class.create({
	RECORD_TIME: 10, //s
	WARN_TIME_REMAINING: 3, //s
	ADD_TIME: 5, //s
	
	counter: null,
	currentInterval: null,
	
	//eventCallbacks
	counterChangedEvent: function(time) {},
	stopEvent: function() {},
	warnTimeRemainingEvent: function(time) {},
	
	initialize: function(options) {
		var me = this;		

		if(!!options.counterChangedEvent) {
			me.counterChangedEvent = options.counterChangedEvent;
		}
		
		if(!!options.stopEvent) {
			me.stopEvent = options.stopEvent;
		}
		
		if(!!options.warnTimeRemainingEvent) {
			me.warnTimeRemainingEvent = options.warnTimeRemainingEvent;
		}
		
	},
	
	start: function() {
		var me = this;		
		me._start(me.RECORD_TIME);
	},
	
	stop: function() {
		var me = this;
		
		me.counter = null;
		clearInterval(me.currentInterval);
		me.currentInterval = null;
		me.stopEvent();	
	},
	
	addTime: function() {
		var me = this;
		
		clearInterval(me.currentInterval);
		me._start(me.counter + me.ADD_TIME);
	},
	
	_start: function(time) {
		var me = this;
		
		me.counter = time;
		me.currentInterval = setInterval(function(){me._secondElapsed();},1000);
		me.counterChangedEvent(me.counter);
	},
	
	_secondElapsed: function() {
		var me = this;
		
		me.counter--;
		
		if (me.counter <= 0) {
			me.stop();
		} else {
			me.counterChangedEvent(me.counter);
			if (me.counter == me.WARN_TIME_REMAINING) {
				me.warnTimeRemainingEvent(me.counter);
			}
		}
	}	
});

